<template>
	<view class="page">
		<!-- 头部标签 -->
		<view class="hear-box" :style="{ paddingTop: winInfo.top + 'px', height: winInfo.height + 'px' }">
			<image src="/static/images/find/xiala.png" @tap="openPopup"></image>
			<view>消息</view>
			<view style="color: #fff">1</view>
			<!-- <image src="/static/images/company/search.svg" v-if="winInfo && winInfo.hostName == 'WeChat'"></image> -->
		</view>
		<!-- 左边弹窗 -->
		<tui-drawer mode="left" :visible="leftPopup" @close="closePopup">
			<view class="popup-info" :style="{ paddingTop: winInfo.top + 'px' }">
				<image src="/static/images/find/xiala.png" class="popup-logo" @tap="closePopup"></image>
				<view class="popup-box">
					<view style="white-space: nowrap">允许他人可以直接联系我</view>
					<switch @change="changeYunxuZJLX" :checked="CurrentUser && CurrentUser.YunxuZJLX" style="transform: scale(0.7)" color="#E1EDF9" />
				</view>
				<!-- <view class="popup-box">
					<view>谁可以给我发消息</view>
					<uni-data-select v-model="value" :localdata="range" @change="change"></uni-data-select>
				</view> -->
			</view>
		</tui-drawer>
		<!-- 头部三个栏目 -->
		<view class="buttom-container">
			<view class="button-box" @tap="ToRenMaiList">
				<view class="message-badge" v-if="TipsCount.renmai">{{ computeCount(TipsCount.renmai) }}</view>
				<image src="/static/images/message/renmai.png"></image>
				<view>人脉和关注</view>
			</view>
			<view class="button-box" @tap="ToZanList">
				<view class="message-badge" v-if="TipsCount.Zan">{{ computeCount(TipsCount.Zan) }}</view>
				<image src="/static/images/message/AIxin.png"></image>
				<view>赞和收藏</view>
			</view>
			<view class="button-box" @tap="ToCommunateList">
				<view class="message-badge" v-if="TipsCount.pinglun">{{ computeCount(TipsCount.pinglun) }}</view>
				<image src="/static/images/message/pinglun.png"></image>
				<view>评论和@</view>
			</view>
		</view>
		<!-- 聊天列表 -->
		<view class="concat-list">
			<view v-if="loading" class="loading-box">
				<view class="loading-item" v-for="i in 3" :key="i">
					<view class="loading-avatar"></view>
					<view class="loading-content">
						<view class="loading-name"></view>
						<view class="loading-message"></view>
					</view>
				</view>
			</view>
			<view v-else v-for="(item, index) in DataList">
				<tui-swipe-action v-if="item.lastMessage" :actions="computeActions(item)" @click="handlerButton($event, index)">
					<template v-slot:content>
						<view class="concat-box" @tap="ChatDetail(item)">
							<image class="concat-Avatar" v-if="item.type == 'chatRoom'" :src="item.Avatar" mode="aspectFill"></image>
							<view class="message-info">
								<view class="message-header" v-if="item.type == 'chatRoom'">
									<view class="concat-Name">{{ item.Name }}</view>
									<view class="concat-time">{{ computeTime(new Date(item.lastMessage.CreateTime)) }}</view>
								</view>
								<view class="message-header">
									<view class="message-line" v-if="item.lastMessage.Leixing != '卡片'">
										{{ item.lastMessage.Leixing == '文字' ? item.lastMessage.Xinxi : `[${item.lastMessage.Leixing}]` }}
									</view>
									<view class="message-line" v-else>
										{{ leixingPan(item.lastMessage.Biaoming) + item.lastMessage.Xinxi }}
									</view>
									<view class="right-box">
										<view v-if="item.NoReadCount > 0" class="weiduCount">{{ item.NoReadCount > 99 ? '99+' : item.NoReadCount }}</view>
										<view
											v-else-if="(item.YonghuID1 == CurrentUser.Id && item.Yonghu1WD) || (item.YonghuID2 == CurrentUser.Id && item.Yonghu2WD)"
											class="weiduCount"
										>
											1
										</view>
										<tui-icon
											v-if="(item.YonghuID1 == CurrentUser.Id && item.Yonghu1ZD) || (item.YonghuID2 == CurrentUser.Id && item.Yonghu2ZD)"
											name="top"
											color="#999"
											size="15"
											bold="true"
										></tui-icon>
									</view>
								</view>
							</view>
						</view>
					</template>
				</tui-swipe-action>
			</view>
		</view>
	</view>

	<!-- 导航栏 -->
	<tabbar currentTab="3" />
</template>

<script>
import tabbar from '/model/tabbar.vue';
import TencentCloudChat from '@tencentcloud/chat';
import TIMUploadPlugin from 'tim-upload-plugin';
import { TUIConversationService } from '@tencentcloud/chat-uikit-engine';
export default {
	components: {
		tabbar
	},

	data() {
		return {
			startTime: 0,
			Islogin: this.Microi.IsLogin(),
			CurrentUser: this.Microi.GetCurrentUser(),
			leftPopup: false,
			winInfo: {},
			currentTab: 0,
			UserSig: '',
			page: 1,
			noData: false,
			DataList: [],
			loading: false,
			tabs: [
				{
					name: '推荐'
				},
				{
					name: '人脉'
				}
			],
			actions: [
				{
					name: '标为未读',
					color: '#fff',
					fontsize: 28, //单位rpx
					width: 74, //单位px
					background: '#FB353B'
				},
				{
					name: '置顶聊天',
					color: '#fff',
					fontsize: 28,
					width: 74,
					background: '#F27500'
				},
				{
					name: '删除',
					width: 74,
					fontsize: 28,
					color: '#fff',
					background: '#FF2442'
				}
			],
			TipsCount: {
				renmai: 0,
				Zan: 0,
				pinglun: 0
			},
			chat: {}
		};
	},
	mounted() {
		let obj = {};
		// #ifdef MP-WEIXIN
		obj = wx.getMenuButtonBoundingClientRect();
		// #endif
		// #ifdef MP-BAIDU
		obj = swan.getMenuButtonBoundingClientRect();
		// #endif
		// #ifdef MP-ALIPAY
		my.hideAddToDesktopMenu();
		// #endif

		setTimeout(() => {
			uni.getSystemInfo({
				success: (res) => {
					this.winInfo = res;
					this.winInfo.width = obj.left || res.windowWidth;
					this.winInfo.tabwidth = this.width * 0.45;
					this.winInfo.height = obj.top ? obj.top + obj.height + 8 : res.statusBarHeight + 44;

					this.winInfo.top = obj.top ? obj.top + (obj.height - 32) / 2 : res.statusBarHeight + 6;

					// if (res.hostName == 'WeChat') {
					// 	this.top = this.top + 30;
					// }
					this.winInfo.scrollH = res.windowWidth;
					if (res.hostName != 'WeChat') {
						uni.hideTabBar();
					}
				}
			});
		}, 0);
	},
	onLoad(options) {
		this.options = options;
		if (this.Islogin) this.Imlogin();
	},
	onShow() {
		this.startTime = new Date();
		this.page = 1;
		this.noData = false;
		if (this.Islogin) this.getDataList();
	},
	onHide() {
		this.chat.logout();
		if (this.Islogin) {
			// 获取当前页面栈
			const pages = getCurrentPages();
			// 获取当前页面的对象
			const currentPage = pages[pages.length - 1];
			// 获取当前页面的路径
			const route = currentPage.route;
			// 获取当前页面的参数
			const options = currentPage.options;
			this.Microi.ApiEngine.Run('Add_liulanLog', {
				YemianCS: options,
				YemianDZ: route,
				LiulanSJC: new Date().getTime() - this.startTime.getTime()
			});
		}
		this.removeMessageListener();
	},
	onUnload() {
		this.chat.logout();
		if (this.Islogin) {
			// 获取当前页面栈
			const pages = getCurrentPages();
			// 获取当前页面的对象
			const currentPage = pages[pages.length - 1];
			// 获取当前页面的路径
			const route = currentPage.route;
			// 获取当前页面的参数
			const options = currentPage.options;
			this.Microi.ApiEngine.Run('Add_liulanLog', {
				YemianCS: options,
				YemianDZ: route,
				LiulanSJC: new Date().getTime() - this.startTime.getTime()
			});
		}
		this.removeMessageListener();
	},
	methods: {
		async Imlogin() {
			var self = this;
			let chat = TencentCloudChat.create({
				SDKAppID: 1600084585
			});
			chat.setLogLevel(0);
			chat.registerPlugin({ 'tim-upload-plugin': TIMUploadPlugin });
			self.chat = chat;
			var UserSig = await this.Microi.ApiEngine.Run('get_Im_UserId', {
				Account: this.CurrentUser.Account
			});
			UserSig = UserSig.Data;
			let promise = chat.login({ userID: this.CurrentUser.Account, userSig: UserSig });
			promise
				.then(function (imResponse) {
					console.log(imResponse.data); // 登录成功
					if (imResponse.data.repeatLogin === true) {
						// 表示账号已登录，本次登录操作为重复登录
						console.log(imResponse.data.errorInfo);
					}
					let onSdkReady = function (event) {
						self.setupMessageListener();
					};
					chat.on(TencentCloudChat.EVENT.SDK_READY, onSdkReady);
				})
				.catch(function (imError) {
					console.warn('login error:', imError); // 错误信息
				});
		},
		leixingPan(name) {
			if (name == 'diy_Biji') {
				return `[笔记]`;
			} else if (name == 'diy_GangweiPJ') {
				return `[岗位评价]`;
			} else if (name == 'sys_user') {
				return `[名片]`;
			} else {
				return `[面经]`;
			}
		},
		// 设置消息监听器
		setupMessageListener() {
			const self = this;
			this.messageListener = function (event) {
				const messageList = event.data;
				console.log(messageList, 'messageList');
				messageList.forEach(async (message) => {
					var index = self.DataList.findIndex((val) => val.Account == message.from);
					console.log(index, 'index');
					var lastMessage = {
						CreateTime: new Date(),
						FasongR: message.from,
						FasongRSC: 0,
						Leixing: '',
						ShipinWJ: '',
						TupianNR: '',
						Xinxi: '',
						Yidu: 0,
						YuyinSC: null
					};
					if (index != -1) {
						if (message.type == 'TIMTextElem') {
							lastMessage.Xinxi = message.payload.text;
							lastMessage.Leixing = '文字';
						} else if (message.type == 'TIMImageElem') {
							lastMessage.TupianNR = message.payload.imageInfoArray[1].url;
							lastMessage.Leixing = '图片';
						} else if (message.type == 'TIMVideoFileElem') {
							lastMessage.ShipinWJ = message.payload.videoUrl;
							lastMessage.Leixing = '视频';
						} else if (message.type == 'TIMSoundElem') {
							lastMessage.ShipinWJ = message.payload.url;
							lastMessage.Leixing = '语音';
							lastMessage.YuyinSC = message.payload.second;
						}
						self.DataList[index].lastMessage = lastMessage;
						self.DataList[index].NoReadCount++;
					}
				});
			};
			// 注册消息监听器
			this.chat.on(TencentCloudChat.EVENT.MESSAGE_RECEIVED, this.messageListener);
		},

		// 移除消息监听器
		removeMessageListener() {
			if (this.messageListener) {
				this.chat.off(TencentCloudChat.EVENT.MESSAGE_RECEIVED, this.messageListener);
				this.messageListener = null;
			}
		},
		handlerButton(e, index) {
			var self = this;
			var info = this.DataList[index];
			var currUseIndex = 1;
			var myYonghuID = this.DataList[index].YonghuID1;
			var noMyYonghuID = this.DataList[index].YonghuID1;
			if (info.YonghuID2 == self.CurrentUser.Id) {
				currUseIndex = 2;
				myYonghuID = this.DataList[index].YonghuID2;
			} else {
				noMyYonghuID = this.DataList[index].YonghuID2;
			}
			if (e.index == 1) {
				self.ChangeRoomType(info.Id, `Yonghu${currUseIndex}ZD`, this.DataList[index][`Yonghu${currUseIndex}ZD`]);
				this.DataList[index][`Yonghu${currUseIndex}ZD`] = this.DataList[index][`Yonghu${currUseIndex}ZD`] * 1 ? 0 : 1;
				this.DataList.sort((a, b) => {
					if (a[`Yonghu${currUseIndex}ZD`] && !b[`Yonghu${currUseIndex}ZD`]) {
						return -1;
					}
					if (!a[`Yonghu${currUseIndex}ZD`] && b[`Yonghu${currUseIndex}ZD`]) {
						return 1;
					}
					return 0;
				});
			} else if (e.index == 0) {
				self.ChangeRoomType(info.Id, `Yonghu${currUseIndex}WD`, this.DataList[index][`Yonghu${currUseIndex}WD`], noMyYonghuID);
				this.DataList[index][`Yonghu${currUseIndex}WD`] = this.DataList[index][`Yonghu${currUseIndex}WD`] * 1 ? 0 : 1;

				this.DataList.sort((a, b) => {
					if (a[`Yonghu${currUseIndex}WD`] && !b[`Yonghu${currUseIndex}WD`]) {
						return -1;
					}
					if (!a[`Yonghu${currUseIndex}WD`] && b[`Yonghu${currUseIndex}WD`]) {
						return 1;
					}
					return 0;
				});
			} else if (e.index == 2) {
				self.Microi.ApiEngine.Run('delete_ChatRoom', {
					Id: info.Id,
					YonghuID: myYonghuID,
					Leixing: `Yonghu${currUseIndex}SC`
				});
				this.DataList.splice(index, 1);
			}
		},
		async ChangeRoomType(Id, Leixing, Type, YonghuID) {
			var self = this;
			var res = await self.Microi.ApiEngine.Run('change_RoomType', {
				Id: Id,
				Leixing: Leixing,
				Type: Type,
				YonghuID: YonghuID
			});
		},
		async ChatDetail(item) {
			var self = this;
			var UserId = await self.Microi.ApiEngine.Run('get_UserInfo', {
				Type: 2,
				Account: item.Account
			});
			var UserSig = await this.Microi.ApiEngine.Run('get_Im_UserId', {
				Account: this.CurrentUser.Account
			});
			UserSig = UserSig.Data;
			uni.setStorageSync('receiverInfo', { userID: item.Account });
			const conversationID = `C2C${item.Account}`;
			uni.navigateTo({
				url: '/pages/message/chatUser?YonghuID=' + UserId.Data + '&conversationID=' + conversationID + '&Account=' + item.Account
			});
		},
		computeActions(item) {
			var actions = [
				{
					name: '标为未读',
					color: '#fff',
					fontsize: 28, //单位rpx
					width: 74, //单位px
					background: '#FB353B'
				},
				{
					name: '置顶聊天',
					color: '#fff',
					fontsize: 28,
					width: 74,
					background: '#F27500'
				},
				{
					name: '删除',
					width: 74,
					fontsize: 28,
					color: '#fff',
					background: '#FF2442'
				}
			];
			if ((item.YonghuID1 == this.CurrentUser.Id && item.Yonghu1ZD) || (item.YonghuID2 == this.CurrentUser.Id && item.Yonghu2ZD)) actions[1].name = '取消置顶';
			if ((item.YonghuID1 == this.CurrentUser.Id && item.Yonghu1WD) || (item.YonghuID2 == this.CurrentUser.Id && item.Yonghu2WD) || item.NoReadCount > 0)
				actions[0].name = '标为已读';
			return actions;
		},
		computeTime(TimeInfo) {
			TimeInfo = new Date(TimeInfo);
			var TimeDay = new Date().setHours(0, 0, 0);
			var Month = TimeInfo.getMonth() + 1;
			if (TimeInfo > TimeDay) {
				return (
					(TimeInfo.getHours() < 10 ? `0${TimeInfo.getHours()}` : TimeInfo.getHours()) +
					':' +
					(TimeInfo.getMinutes() < 10 ? `0${TimeInfo.getMinutes()}` : TimeInfo.getMinutes())
				);
			} else {
				return TimeInfo.getFullYear() + '-' + (Month < 10 ? `0${Month}` : Month) + '-' + (TimeInfo.getDate() < 10 ? `0${TimeInfo.getDate()}` : TimeInfo.getDate());
			}
		},
		async getDataList() {
			var self = this;
			if (!this.Islogin) {
				return;
			} else {
				this.loading = true;
				var res = await self.Microi.ApiEngine.Run('get_MessageList', {
					page: self.page,
					YonghuID: self.CurrentUser?.Id
				});
				if (this.Islogin) {
					self.CurrentUser.YunxuZJLX = res.YunxuZJLX;
				}

				if (self.page == 1) {
					self.TipsCount = res.TipsCount;
					self.DataList = res.Data;
				} else {
					self.DataList.push(...res.Data);
				}
				if (!res.Data.length) {
					self.noData = true;
				} else {
					self.page++;
				}
				this.loading = false;
			}
		},

		ToRenMaiList() {
			this.Microi.CheckLogin();
			uni.navigateTo({
				url: '/pages/message/Renmai'
			});
		},
		computeCount(num) {
			if (num > 99) {
				return '99+';
			} else {
				return num;
			}
		},
		ToZanList() {
			this.Microi.CheckLogin();
			uni.navigateTo({
				url: '/pages/message/Zan'
			});
		},
		ToCommunateList() {
			this.Microi.CheckLogin();
			uni.navigateTo({
				url: '/pages/message/Communate'
			});
		},
		openPopup() {
			this.leftPopup = true;
		},
		closePopup() {
			this.leftPopup = false;
		},
		changeYunxuZJLX() {
			var YunxuZJLX = this.CurrentUser.YunxuZJLX;
			this.Microi.FormEngine.UptFormData({
				FormEngineKey: 'sys_user',
				Id: this.CurrentUser.Id,
				_RowModel: {
					YunxuZJLX: YunxuZJLX ? 0 : 1
				}
			});
			this.CurrentUser.YunxuZJLX = YunxuZJLX ? 0 : 1;
		},
		change(e) {
			this.currentTab = e.index;
		}
	},
	onReachBottom() {
		if (this.noData) {
			this.Microi.Tips('暂无更多消息', false);
			return;
		} else {
			this.getDataList();
		}
	},
	onPullDownRefresh() {
		this.page = 1;
		this.noData = false;
		this.DataList = [];
		if (this.Islogin) this.getDataList();
		setTimeout(function () {
			uni.stopPullDownRefresh();
		}, 500);
	}
};
</script>

<style>
.page {
	background-color: #fff;
	padding-bottom: 150rpx;
}
.hear-box {
	display: flex;
	align-items: center;
	justify-content: space-between;
	background-color: #ffffff;
	box-sizing: border-box;
	padding: 20rpx;
	border: 2rpx solid #f4f5f6;
}
.hear-box image {
	width: 40rpx;
	height: 40rpx;
}
.popup-info {
	height: 100vh;
	padding: 20rpx;
	width: 520rpx;

	background: #eef0f1;
	border-radius: 78rpx 0rpx 0rpx 78rpx;
}

.popup-logo {
	width: 40rpx;
	height: 40rpx;
}
.popup-box {
	display: flex;
	align-items: center;
	justify-content: space-between;
	background-color: #fff;
	margin-bottom: 20rpx;
	box-sizing: border-box;
	width: 456rpx;
	height: 88rpx;
	padding: 20rpx;
	background: #ffffff;
	border-radius: 16rpx 16rpx 16rpx 16rpx;
	border: 1rpx solid #f3f5f9;

	font-weight: 500;
	font-size: 28rpx;
	color: #333333;
	line-height: 33rpx;
	text-align: left;
	font-style: normal;
	text-transform: none;
}
.popup-box image {
	width: 40rpx;
	height: 40rpx;
	margin-right: 20rpx;
}
.buttom-container {
	margin: 20rpx 16rpx;
	display: flex;
	align-items: center;
	justify-content: space-between;
}
.button-box {
	width: 240rpx;
	height: 216rpx;
	border-radius: 16rpx 16rpx 16rpx 16rpx;

	font-weight: 500;
	font-size: 28rpx;
	color: #000000;
	line-height: 33rpx;
	display: flex;
	justify-content: center;
	align-items: center;
	flex-direction: column;
	text-align: center;
	font-style: normal;
	text-transform: none;

	position: relative;
}
.message-badge {
	position: absolute;
	top: 28rpx;
	right: 38rpx;

	width: 60rpx;
	height: 32rpx;
	background: #ea3325;
	border-radius: 118rpx 118rpx 118rpx 118rpx;

	font-weight: 400;
	font-size: 24rpx;
	color: #ffffff;
	line-height: 32rpx;
	text-align: center;
	font-style: normal;
	text-transform: none;
	z-index: 990;
}
.button-box image {
	width: 102rpx;
	height: 102rpx;
	margin-bottom: 16rpx;
}
.concat-list {
	/* padding: 16rpx; */
}
.concat-box {
	width: 100%;
	height: 158rpx;
	background: #ffffff;
	border-radius: 0rpx 0rpx 0rpx 0rpx;
	border-bottom: 2rpx solid #f2f2f2;
	display: flex;
	align-items: center;
	justify-content: flex-start;
	padding: 26rpx 24rpx;
	box-sizing: border-box;
	gap: 32rpx;
}
.concat-Avatar {
	width: 108rpx;
	height: 108rpx;
	border-radius: 50%;
}
.message-info {
	display: flex;
	justify-content: center;
	flex-direction: column;
	gap: 18rpx;
	width: 532rpx;
}
.message-header {
	width: 100%;
	display: flex;
	justify-content: space-between;
}
.message-header .right-box {
	display: flex;
	align-items: center;
	justify-content: flex-start;
	gap: 15rpx;
}
.concat-Name {
	font-family: PingFang SC, PingFang SC;
	font-size: 36rpx;
	color: #000000;
	text-align: left;
	font-style: normal;
	text-transform: none;
}
.concat-time {
	font-family: PingFang SC, PingFang SC;
	font-size: 28rpx;
	color: #999999;
	text-align: right;
	font-style: normal;
	text-transform: none;
}
.message-line {
	width: 466rpx;
	height: 40rpx;
	font-family: PingFang SC, PingFang SC;
	font-size: 28rpx;
	color: #999999;
	text-align: left;
	font-style: normal;
	text-transform: none;
	display: -webkit-box;
	-webkit-box-orient: vertical;
	-webkit-line-clamp: 1;
	overflow: hidden;
	text-overflow: ellipsis;
	word-wrap: break-word;
}
.weiduCount {
	/* position: absolute;
	right: 0;
	top: 0; */
	width: 34rpx;
	height: 34rpx;
	background: #ea3325;
	border-radius: 50%;
	font-family: PingFang SC, PingFang SC;
	font-size: 24rpx;
	color: #ffffff;
	line-height: 34rpx;
	text-align: center;
	font-style: normal;
	text-transform: none;
}
.loading-box {
	padding: 20rpx;
}
.loading-item {
	display: flex;
	align-items: center;
	margin-bottom: 20rpx;
}
.loading-avatar {
	width: 108rpx;
	height: 108rpx;
	border-radius: 50%;
	background: #f5f5f5;
	animation: loading 1.5s infinite;
}
.loading-content {
	flex: 1;
	margin-left: 32rpx;
}
.loading-name {
	width: 200rpx;
	height: 36rpx;
	background: #f5f5f5;
	margin-bottom: 18rpx;
	animation: loading 1.5s infinite;
}
.loading-message {
	width: 400rpx;
	height: 28rpx;
	background: #f5f5f5;
	animation: loading 1.5s infinite;
}
@keyframes loading {
	0% {
		opacity: 0.6;
	}
	50% {
		opacity: 1;
	}
	100% {
		opacity: 0.6;
	}
}
</style>
